/**
 * @author ccpalu
 */

function getKey(ans1){
/* It access the answer (ans1) from search and find the key value.
 * This key will be used after to make new searches on this database,
 * without login. So, the key value is saved in the TCGA object
 * in order to be easily accessed by other functions.
 * 
 * After, the database is consulted to obtain the information of 
 * the colection 'Samples' which id is 47. This colection contains
 * the bar code of all patients and also relates it with the segmented
 * data.
 */
		
	var s3db=document.createElement('OBJECT');
	s3db.id='s3db';
	s3db.index=0;
	s3db.rules=new Array();
	s3db.project = function(){
		return document.getElementById('selectProject').value;
	};
	
	s3db.url=document.getElementById('domainId').value;//'http://ibl.mdanderson.org/similarity';
	
	s3db.key = ans1[0].key_id;
	s3db.done=false;

	document.getElementsByTagName('head')[0].appendChild(s3db);

	loadingStatus('Accessing projects on S3DB');

	doS3qlQuery('projects', '', 'listProject(ans)', 'project_id,name,description');
		
	return false;
}

function doS3qlQuery(from, where,callFunction, select){
	var s3db = document.getElementById('s3db');
	if (!select){
		select='*';
	}
	if (document.getElementById('selectProject')){
		where = '<project_id>'+s3db.project()+'</project_id>'+where;
	}
	var url = s3db.url+ '/S3QL.php?query=<S3QL><key>'+ s3db.key+'</key><select>'+select+'</select><from>'+
		from+'</from><where>'+ where + '</where></S3QL>';
	s3db_jsonpp_call(url, callFunction);
	
	return false;
}

function listProject(ans){
	remove_element_by_id("LoadingStatus");
	document.body.style.cursor="auto";

	if (ans[0] == undefined) {
		alert("No projects were found.");
	}
	else {
		if (ans[0].error_code) {
			alert(ans[0].message);
		}
		else {
			remove_element_by_id('projectListD');
			document.getElementById('fileLoginForm').style.display = 'none';
			
			var projectListD = document.createElement('DIV');
			projectListD.id = 'projectListD';
			setPosition(projectListD, 15, 1);
			document.getElementById('sourceDiv').appendChild(projectListD);
			
			var s3dbLogo = document.createElement('IMG');
			projectListD.appendChild(s3dbLogo);
			s3dbLogo.id = 's3dbLogo2';
			s3dbLogo.src = 'http://cnviewer.googlecode.com/hg/Images/s3db.png';
			resize(s3dbLogo, 40);
			setPosition(s3dbLogo, 35, 25, 'absolute');
			
			var divTitle = createParagraph('selectProjectP', 'Choose a Project', projectListD);
			divTitle.style.width = "200px";
			setFont(divTitle, '18px', 0, 0, 0);
			setPosition(divTitle, 80, 30, 'absolute');
			
			var selectProject = document.createElement('SELECT');
			selectProject.id = 'selectProject';
			selectProject.name = 'selectProject';
			selectProject.style.width = "225px";
			selectProject.onchange = showProjectDescription;
			projectListD.appendChild(selectProject);
			
			for (var i = 0; i < ans.length; i++) {
				selectProject.options[i] = new Option(ans[i].name, ans[i].project_id);
				selectProject.options[i].description = ans[i].description;
			}
			setPosition(selectProject, 25, 70, 'absolute');
			
			var projectDescription = createParagraph('projectDescription', selectProject.options[0].description, projectListD);
			projectDescription.style.width = "225px";
			projectDescription.style.height = "50px";
			projectDescription.style.overflow='hidden';
			setFont(projectDescription, '13px', 0, 0, 0);
			setPosition(projectDescription, 25,102, 'absolute');
			projectListD.appendChild(projectDescription);
			
			var accessButton = document.createElement('INPUT');
			accessButton.type='button';
			accessButton.id='accessButton';
			accessButton.name='accessButton';
			accessButton.value='Access';
			accessButton.onclick=getRules;
			projectListD.appendChild(accessButton);
			setPosition(accessButton, 190, 143,'absolute');
		}
	}
	return false;
}

function showProjectDescription(){
	if (this.options[this.selectedIndex].description) {
		document.getElementById('projectDescription').innerHTML = this.options[this.selectedIndex].description;
	}
	else {
		document.getElementById('projectDescription').innerHTML = 'No description available';
		document.getElementById('projectDescription').style.fontStyle="italic";
	}

return false;
}

function getRules(){
	loadingStatus('Reading project<br>information');
	doS3qlQuery('rules', '<subject>Samples</subject><object>Name</object>','s3dbRules( "sampleName", ans)');
	doS3qlQuery('rules', '<subject>Samples</subject><object>Segmented Data</object>','s3dbRules("sampleSegmented", ans)');
	doS3qlQuery('rules', '<subject>Segmented Data</subject><object>File</object>','s3dbRules("segmentedFile", ans)');
	doS3qlQuery('rules', '<subject>Probe Map</subject><object>File</object>','s3dbRules("mapFile", ans)');
	closeUploadBox();
	return false;
}

function s3dbRules(rule, ans){
	
	if (ans[0]==undefined){
		var error;
		
		switch (rule){
			case 'sampleName':
			error = "\nThe SUBJECT 'Samples' and/or the OBJECT 'Name' were not found.";
			break;
			case 'sampleSegmented':
			error = "\nThe SUBJECT 'Samples' and/or the OBJECT 'Segmented Data' were not found.";
			break;
			case 'segmentedFile':
				error = "\nThe SUBJECT 'Segmented Data' and/or the OBJECT 'File' were not found.";
			break;
			case 'mapFile':
				error = "\nThe SUBJECT 'Map' and/or the OBJECT 'File' were not found.";
			break;
			default:
			error = "";
		}
		alert("This Project doesn't have a suitable data format." + error );
		document.body.style.cursor="auto";
	}
	var s3db = document.getElementById('s3db');
	s3db.rules[rule]=ans[0].rule_id;

	if ((!s3db.done)&&(s3db.rules.sampleName!=undefined)&&(s3db.rules.sampleSegmented!=undefined)){
		var url = s3db.url+'/sparql.php?key='+s3db.key+'&query=SELECT*WHERE{?Samples :R'+s3db.rules.sampleName+' ?Name .?Samples :R'+s3db.rules.sampleSegmented+' ?SegmentedData .}&clean=1';
		s3db_jsonpp_call(url, 'dataCorrespondence(ans)');
		s3db.done=true;		
	}
	return false;
}

function dataCorrespondence(mapping){

	var cnv = document.getElementById('CNV');
	var s3db = document.getElementById('s3db');
	var selectSample = document.getElementById('choose_sample');
	loadingStatus('Downloading CNV data... <br>It may take a few minutes');	
	cnv.analysisTitle = document.getElementById('selectProject').options[document.getElementById('selectProject').selectedIndex].innerHTML;

	for (var i=0; i< mapping.length; i=i+1){
	
		var selectSample = document.getElementById('choose_sample');
		cnv.mapAnswer[i]=mapping[i];
		
		selectSample.options[selectSample.options.length] = new Option(mapping[i].Name, mapping[i].SegmentedData.replace(s3db.url+'/I',""));
	}

	getStatements();
	return false;	
}

function s3db_jsonpp_call(src, next_eval){
	document.body.style.cursor="wait";
	var call = "call_" + Math.random().toString().replace(/\./g, "");
	var headID = document.getElementsByTagName("head")[0];
	var script = document.createElement('script');
	script.id = call;
	script.type = 'text/javascript';
	// using padded, parameterized JSON
	
	src = src + "&format=json&jsonp=s3db_jsonpp&jsonpp=" + next_eval + "&onload=remove_element_by_id('" + script.id + "')";
	script.src = src;
	try {
		headID.appendChild(script); // retrieve answer
	}
	catch(e){
		consle.log("!! "+e);
	}
	return false;
}
 
function remove_element_by_id(id){

	try {
		var e = document.getElementById(id);
		e.parentNode.removeChild(e);
	} 
	catch (temp) {
	
	}
	
	return false;
}

function s3db_jsonpp (ans,jsonpp) {
	try{
	eval(jsonpp);
	}
	catch(e){
	//	console.log("srdb_jsonpp error " + e);
		remove_element_by_id('LoadingStatus');
	}
    return ans;
}
